
package controllers;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import models.re.Re;
import controllers.Actor.ThreadCount;
import play.data.Form;
import play.mvc.Result;

/**
 * 
 * @author lulhum@lulhum.org
 */
// @Restrict("admin")
public class Recommendation extends Application {
	
	private static volatile ActorRef launcher = null;
	
	public static Result index() {
		Form<ThreadCount> form = play.data.Form.form(ThreadCount.class).bindFromRequest();
		if (request().method() == "GET") {
			return ok(views.html.recommendation.index.render(form));
        }

        if (form.hasErrors()) {
            flash("error", "Invalid number");
            return badRequest(views.html.recommendation.index.render(form));
        } else {
            int count = form.get().count;
            return start(count);
        }
	}
	
    public static Result start(final int count) {
    	if(!Re.Launcher.busy) {
	        //crawler().start(count);    		
    		if(launcher==null) {
    			ActorSystem system = ActorSystem.create("LaunchAAA");
    			Props props = new Props(new UntypedActorFactory() {
    				private static final long serialVersionUID = 1L;
    				public UntypedActor create() {
    					return new Re.Launcher();
    				}
    			});
    			props.withDispatcher("nomailbox-dispatcher");
	    		launcher = system.actorOf(props, "master");
    		}
    		launcher.tell(new Re.Start(count),null);
	        flash("success", "Started");
	        return redirect(routes.Recommendation.index());
	    }
    	flash("error","Running");
		return redirect(routes.Recommendation.index());        
    }


}
